﻿using IdentityModel;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using ZhCun.WebUtils.Configs;

namespace ZhCun.WebUtils
{
    /// <summary>
    /// token中的用户信息
    /// </summary>
    public class SessionUser
    {
        /// <summary>
        /// 当前用户Id
        /// </summary>
        public string UserId { set; get; }
        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName { set; get; }
        /// <summary>
        /// 角色
        /// </summary>
        public string RoleId { set; get; }
    }

    /// <summary>
    /// jwt 操作类
    /// </summary>
    public static class JwtHelper
    {
        /// <summary>
        /// 创建一个token
        /// </summary>
        public static string CreateToken(SessionUser user, TimeSpan expires, DateTime? notBefore = null)
        {
            var claims = new[]
            {
                new Claim(JwtClaimTypes.Id, user.UserId),
                new Claim(JwtClaimTypes.Name, user.UserName),
                new Claim(JwtClaimTypes.Role, user.RoleId),

                //new Claim(nameof(user.UserId), user.UserId),
                //new Claim(nameof(user.UserName), user.UserName),
                //new Claim(nameof(user.RoleId), user.RoleId),
                //new Claim("RefreshToken","123")
            };
            var key = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(JwtConfig.THIS.SecretKey));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                JwtConfig.THIS.Issuer,
                JwtConfig.THIS.Audience,
                claims,
                notBefore: notBefore,
                expires: DateTime.Now.Add(expires),
                signingCredentials: credentials
            );
            return new JwtSecurityTokenHandler().WriteToken(token);
        }

        public static JwtSecurityToken GetJwtToken(string accessToken)
        {
            var token = new JwtSecurityToken(accessToken.Substring(7));
            return token;
        }

        public static SessionUser GetSessionUser(string accessToken)
        {
            var token = GetJwtToken(accessToken);
            SessionUser user = new SessionUser
            {
                UserId = token.Claims.First(s => s.Type == JwtClaimTypes.Id).Value,
                UserName = token.Claims.First(s => s.Type == JwtClaimTypes.Name).Value,
                RoleId = token.Claims.First(s => s.Type == JwtClaimTypes.Role).Value
            };
            return user;
        }
    }
}
